//
//  MapViewController.m
//  ITASTRA
//
//  Created by me on 8/4/12.
//  Copyright (c) 2012 me. All rights reserved.
//

#import "MapViewController.h"
#import "MapDetailViewController.h"




@implementation MapViewController
@synthesize indicatorMapview, mapView;
@synthesize theList;
//@synthesize chooseTypeMap;







- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}




- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"itStr.png"]];
    imageView.frame = CGRectMake(0, 0, 320, 45); //change height and width accordingly
    [self.navigationController.navigationBar addSubview:imageView];
    self.navigationController.navigationBar.tintColor = [UIColor colorWithRed:194/255.0f green:194/255.0f blue:194/255.0f alpha:1];
    self.navigationController.toolbar.tintColor = [UIColor colorWithRed:194/255.0f green:194/255.0f blue:194/255.0f alpha:1];
    self.navigationController.navigationBar.frame = CGRectMake(0.0, 20.0, 320.0, 90.0);
    
}




- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    // Check if this is the first time we get a reading.
    if (currentPosition == nil) {
        // Create a map point from the coordinate.
        MKMapPoint point = MKMapPointForCoordinate(newLocation.coordinate);
        // Get the relationship between map points and metres at our current latitude.
        double pointsPerMeter = MKMapPointsPerMeterAtLatitude(newLocation.coordinate.latitude);
        // Calculate the number of map points that equals a distance of 500m.
        double visibleDistance = pointsPerMeter * 500.0;
        
        // Create a rectangle that is a kilometer at the sides and is centered on our position.
        MKMapRect rect = MKMapRectMake(
                                       point.x - visibleDistance, point.y - visibleDistance,
                                       visibleDistance * 2, visibleDistance * 2);
        
        // Tell the map view to show the rectangle.
        [self.mapView setVisibleMapRect:rect animated:YES];
        
        MapAnnotationController *annotation = [[MapAnnotationController alloc] initWithCoordinate:newLocation.coordinate];
        annotation.nomeAnnotation = @"nome";//theList.name;
        annotation.descriptionAnnotation = @"description";//theList.description;
        annotation.info1Annotation = @"info1";//theList.info1;
        
    //    NSString *old_Stra_Photo = theList.stra_photo;
    //    NSString *path = [old_Stra_Photo stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
        NSURL *url = [NSURL URLWithString:@"red.png"];
        NSData *data = [NSData dataWithContentsOfURL:url];
        UIImage *imgTemp = [[UIImage alloc] initWithData:data];
        
        
        annotation.imageAnnotation = imgTemp;
        [self.mapView addAnnotation:annotation];
    }
    // Update the current position.
    currentPosition = newLocation;
}

-(MKAnnotationView *)mapView:(MKMapView *)view viewForAnnotation:(id<MKAnnotation>)annotation {
    MKPinAnnotationView *pin = nil;
    
    //Check if the annotation is of our annotation class
    if ([annotation isKindOfClass:[MapAnnotationController class]]) {
        NSString *pinIdentifier = @"red_pin";
        // Get a pin for re-use
        pin = (MKPinAnnotationView*)[view dequeueReusableAnnotationViewWithIdentifier:pinIdentifier];
        if (!pin) {
            // If no pin was available for re-use we'll create a new one.
            pin = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pinIdentifier];
            pin.pinColor = MKPinAnnotationColorGreen;
            pin.canShowCallout = YES;
            pin.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
            pin.animatesDrop = YES;
        }
        else {
            // Update the annotation if we're re-using an old pin
            pin.annotation = annotation;
        }
    }
    
    return pin;
}

-(void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control{
    //Check if the annotation is of our annotation class
    if ([view.annotation isKindOfClass:[MapAnnotationController class]]) {
        // Store a reference to the annotation so that we can pass it on in prepare for segue.
        selectedAnnotation = view.annotation;
        [self performSegueWithIdentifier:@"showPinDetails" sender:self];
    }
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Check that the segue is our showPinDetails-segue
    if ([segue.identifier isEqualToString:@"showPinDetails"]) {
        // Pass the annotation reference to the detail view controller.
        MapDetailViewController *detail = [segue destinationViewController];
        detail.annotation = selectedAnnotation;
    }
}



- (IBAction)setMapType:(id)sender
{
    switch (((UISegmentedControl *)sender).selectedSegmentIndex)
    {
        case 0:
        {
            mapView.mapType = MKMapTypeStandard;
            break;
        }
        case 1:
        {
            mapView.mapType = MKMapTypeSatellite;
            break;
        }
        default:
        {
            mapView.mapType = MKMapTypeHybrid;
            break;
        }
    }
}




#pragma mark - View lifecycle

- (void)viewDidLoad
{
    
    [super viewDidLoad];
	
    // Check if the user has enabled location services.
    if ([CLLocationManager locationServicesEnabled]) {
        // Create a location manager.
        locationManager = [[CLLocationManager alloc] init];
        // Set ourselves as it's delegate so that we get notified of position updates.
        locationManager.delegate = self;
        // Set the desired accuracy.
        locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        // Start tracking.
        [locationManager startUpdatingLocation];
        
    }
    
    // Add a long press gesture recognizer to the map for adding new pins to the map
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(mapLongPress:)];
    longPress.minimumPressDuration = 1.0;
    [self.mapView addGestureRecognizer:longPress];
}

-(void)mapLongPress:(UIGestureRecognizer*)gesture {
    if (gesture.state != UIGestureRecognizerStateBegan)
        return;
    
    // Get the screen coordinates for the touch relative to our map view.
    CGPoint point = [gesture locationInView:self.mapView];
    // Get the world coordinates that corresponds to the screen coordinates.
    CLLocationCoordinate2D coordinates = [self.mapView convertPoint:point toCoordinateFromView:self.mapView];
    
    MapAnnotationController *annotation = [[MapAnnotationController alloc] initWithCoordinate:coordinates];
    annotation.nomeAnnotation = @"Dropped pin";
    [self.mapView addAnnotation:annotation];
}

- (void)viewDidUnload
{   
    self.mapView = nil;
    [self setMapView:nil];
//    [self setChooseTypeMap:nil];
    [super viewDidUnload];
    
    [locationManager stopUpdatingLocation];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}


- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
	[super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}




@end




/*
 - (void)loadView {
 self.title = @"Mappa";
 MKMapView *map= [[MKMapView alloc] init];
 map.delegate = self;
 map.showsUserLocation = YES;
 self.view = map;
 [map addAnnotation:[[MapViewAnnotation alloc] init] ];
 
 }
 
 
 - (void)viewDidAppear:(BOOL)animated {
 [super viewDidAppear:animated];
 UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"itStr.png"]];
 imageView.frame = CGRectMake(0, 0, 320, 45); //change height and width accordingly
 [self.navigationController.navigationBar addSubview:imageView];
 self.navigationController.navigationBar.tintColor = [UIColor colorWithRed:194/255.0f green:194/255.0f blue:194/255.0f alpha:1];
 self.navigationController.toolbar.tintColor = [UIColor colorWithRed:194/255.0f green:194/255.0f blue:194/255.0f alpha:1];
 self.navigationController.navigationBar.frame = CGRectMake(0.0, 20.0, 320.0, 90.0);
 }
 
 
 
 
 - (void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)views {
 for (MKAnnotationView *annotationView in views) {
 if (annotationView.annotation == mapView.userLocation) {
 MKCoordinateSpan span = MKCoordinateSpanMake(0.01, 0.01);
 MKCoordinateRegion region = MKCoordinateRegionMake(mapView.userLocation.coordinate, span);
 [mapView setRegion:region animated:YES];
 }
 }
 }
 
 
 - (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id )annotation {
 if (annotation == mapView.userLocation) {
 return nil;
 }
 MKPinAnnotationView *pinView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"Pin"];
 pinView.pinColor = MKPinAnnotationColorPurple;
 pinView.canShowCallout = YES;
 pinView.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
 pinView.animatesDrop = YES;
 return pinView;
 }
 
 // When the view loads
 - (void)viewDidLoad
 {
 // Set some coordinates for our position (Buckingham Palace!)
 CLLocationCoordinate2D location;
 location.latitude = (double) 51.501468;
 location.longitude = (double) -0.141596;
 [indicatorMapview startAnimating];
 self.navigationItem.prompt = @"";
 UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"itStr.png"]];
 imageView.frame = CGRectMake(0, 0, 320, 45); //change height and width accordingly
 [self.navigationController.navigationBar addSubview:imageView];
 
 
 // Add the annotation to our map view
 
 }
 
 
 
 
 
 
 
 // When a map annotation point is added, zoom to it (1500 range)
 
 // Received memory warning
 - (void)didReceiveMemoryWarning {
 [super didReceiveMemoryWarning];
 }
 
 // If the view unloads, release the map view
 - (void)viewDidUnload {
 [self setIndicatorMapview:nil];
 [super viewDidUnload];
 [indicatorMapview stopAnimating];
 }
 
 
 // Deallocations
 
 @end
 
 
 */